//
//  ZJTimer.swift
//  ZJTimerDemo
//
//  Created by Javen on 2019/3/8.
//  Copyright © 2019 Javen. All rights reserved.
//

import UIKit

open class ZJTimer: NSObject {
    private(set) var _timer: Timer!
    fileprivate weak var _aTarget: AnyObject!
    fileprivate var _aSelector: Selector!
    public var fireDate: Date {
        get{
            return _timer.fireDate
        }
        set{
            _timer.fireDate = newValue
        }
    }
    
    public class func scheduledTimer(timeInterval ti: TimeInterval, target aTarget: AnyObject, selector aSelector: Selector, userInfo: Any?, repeats yesOrNo: Bool) -> ZJTimer {
        let timer = ZJTimer()
        
        timer._aTarget = aTarget
        timer._aSelector = aSelector
        timer._timer = Timer.scheduledTimer(timeInterval: ti, target: timer, selector: #selector(ZJTimer.zj_timerRun), userInfo: userInfo, repeats: yesOrNo)
        return timer
    }
    
    public func fire() {
        _timer.fire()
    }
    
    public func invalidate() {
        _timer.invalidate()
    }
    
    @objc func zj_timerRun() {
        //如果崩在这里，说明你没有在使用Timer的VC里面的deinit方法里调用invalidate()方法
        _ = _aTarget.perform(_aSelector)
    }
    
    deinit {
        print("计时器已销毁")
    }
}




open class ZJKillTimer {
    /// 活动结束秒数
    public var secondsToEnd: Int = 0
    public var myTimer: ZJTimer!
    public var callBack: ((String)->())?
    
    public init(seconds: Int, callBack: ((String)->())?) {
        self.secondsToEnd = seconds
        myTimer = ZJTimer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerRun), userInfo: nil, repeats: true)
        //如果希望对Timer做自定义的操作，使用_Timer属性
        RunLoop.current.add(myTimer._timer, forMode: RunLoop.Mode.common)
        myTimer.fire()
        self.callBack = callBack
    }
    
    deinit {
        myTimer.invalidate()
    }
    
    @objc func timerRun() {
        secondsToEnd -= 1
        if secondsToEnd == 0 {
            myTimer.invalidate()
        }
        callBack?(secondsToTimeString(seconds: secondsToEnd))
        
    }
    /// 秒数转化为时间字符串
    public func secondsToTimeString(seconds: Int) -> String {
        if seconds == 0{
            return "订单已结束"
        }
        //天数计算
        _ = (seconds)/(24*3600);
        
        //小时计算
        let hours = (seconds)%(24*3600)/3600;
        
        //分钟计算
        let minutes = (seconds)%3600/60;
        
        //秒计算
        let second = (seconds)%60;
        
        let timeString  = String(format: "%02lu时%02lu分%02lu秒",hours, minutes, second)
        return timeString
    }

}
